package org.znxs.znxsojquestion.services.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.znxs.common.common.ErrorCode;
import org.znxs.common.constant.CommonConstant;
import org.znxs.common.exception.BusinessException;
import org.znxs.common.exception.ThrowUtils;
import org.znxs.common.utils.SqlUtils;
import org.znxs.model.model.dto.questionsubmit.QuestionSubmitAddRequest;
import org.znxs.model.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import org.znxs.model.model.entity.Question;
import org.znxs.model.model.entity.QuestionSubmit;
import org.znxs.model.model.entity.User;
import org.znxs.model.model.enums.QuestionSubmitLanguageEnum;
import org.znxs.model.model.enums.QuestionSubmitStatusEnum;
import org.znxs.model.model.vo.QuestionSubmitVO;
import org.znxs.model.model.vo.QuestionVO;
import org.znxs.model.model.vo.UserVO;
import org.znxs.znxsojquestion.mapper.QuestionSubmitMapper;
import org.znxs.znxsojquestion.rabbitMq.MyMessageProducer;
import org.znxs.znxsojquestion.services.QuestionService;
import org.znxs.znxsojquestion.services.QuestionSubmitService;
import org.znxs.znxsojservice.services.JudgeFeignClient;
import org.znxs.znxsojservice.services.UserFeignClient;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author administer
 * @description 针对表【question_submit(题目提交记录)】的数据库操作Service实现
 * @createDate 2024-11-10 17:48:06
 */
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
        implements QuestionSubmitService {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserFeignClient userFeignClient;

    @Resource
    @Lazy
    private JudgeFeignClient judgeFeignClient;

    @Resource
    private MyMessageProducer myMessageProducer;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest 提交题目添加请求
     * @param loginUser
     * @return
     */
    @Override
    public Long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        // 判断实体是否存在，根据类别获取实体
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);

        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //  校验编程语言是否合理
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if (languageEnum == null) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "编程语言不存在");
        }
        long userId = loginUser.getId();
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(language);
        // 设置状态 设置为等待状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");

        // 每个用户串行提交题目
        // 锁必须要包裹住事务方法 (以后再处理)

        // 是否已提交题目  已提交题目设置为取消提交
        boolean save = this.saveOrUpdate(questionSubmit);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "插入提交表失败");
        Long questionSubmitId = questionSubmit.getId();

        // 使用消息队列
        myMessageProducer.sendMessage("code_exchange", "my_routingKey", String.valueOf(questionSubmitId));

//        // 执行判题服务
//        CompletableFuture.runAsync(() -> {
//            judgeFeignClient.doJudge(questionSubmitId);
//        });


        return questionSubmitId;
    }

    /**
     * 封装了事务的方法
     *
     * @param userId
     * @param questionId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int doQuestionSubmitInner(long userId, long questionId) {
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        QueryWrapper<QuestionSubmit> thumbQueryWrapper = new QueryWrapper<>(questionSubmit);
        QuestionSubmit oldQuestionSubmit = this.getOne(thumbQueryWrapper);
        boolean result;
        // 已提交题目
        if (oldQuestionSubmit != null) {
            result = this.remove(thumbQueryWrapper);
            if (result) {
                // 提交题目数 - 1
                result = questionService.update()
                        .eq("id", questionId)
                        .gt("thumbNum", 0)
                        .setSql("thumbNum = thumbNum - 1")
                        .update();
                return result ? -1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        } else {
            // 未提交题目
            result = this.save(questionSubmit);
            if (result) {
                // 提交题目数 + 1
                result = questionService.update()
                        .eq("id", questionId)
                        .setSql("thumbNum = thumbNum + 1")
                        .update();
                return result ? 1 : 0;
            } else {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }
        }
    }


    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        // 非空校验
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }

        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();
        Long userId = questionSubmitQueryRequest.getUserId();


        // 拼接查询条件
        queryWrapper.eq(StrUtil.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User currentUser) {
        // 转换成vo
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        // 如果不为管理员或者本人
        if (!userFeignClient.isAdmin(currentUser) || !Objects.equals(currentUser.getId(), questionSubmit.getUserId())) {
            questionSubmitVO.setCode(null);
        }
        // 查询创建用户信息
        User createUser = userFeignClient.getById(questionSubmit.getUserId());
        // 保存创建用户vo
        UserVO createUserVO = UserVO.objToVo(createUser);
        // 查询题目信息
        Question question = questionService.getById(questionSubmit.getQuestionId());
        // 封装vo
        QuestionVO questionVO = QuestionVO.objToVo(question);
        // 存入该题目创建用户信息
        questionVO.setUserVO(createUserVO);
        // 封装vo
        questionSubmitVO.setQuestionVO(questionVO);
        // 封装当前用户vo
        questionSubmitVO.setUserVO(UserVO.objToVo(currentUser));
        return questionSubmitVO;
    }

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User currentUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        // 非空判断
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        // 先根据ids查出所有的用户 以及所有的题目
        Set<Long> submitUserIdSet = new HashSet<>();
        Set<Long> questionIdSet = new HashSet<>();
        questionSubmitList.forEach(questionSubmit -> {
            submitUserIdSet.add(questionSubmit.getUserId());
            questionIdSet.add(questionSubmit.getQuestionId());
        });


        // 提交题目id 与 提交 题目的map映射
        Map<Long, List<Question>> userIdQuestionListMap = questionService.listByIds(questionIdSet).stream().collect(Collectors.groupingBy(Question::getId));

        // 根据查询出来的题目进行查询创建用户set  保存题目创建用户id到createUserIds集合中
        HashSet<Long> createUserIds = new HashSet<>();
        userIdQuestionListMap.forEach((aLong, questions) -> {
            createUserIds.add(questions.get(0).getUserId());
        });


        // todo 没有进行非空判断 若set为零需要再做处理
        // 提交题目用户id 提交用户的map映射
        Map<Long, List<User>> submitUserIdUserListMap = userFeignClient.listByIds(submitUserIdSet).stream().collect(Collectors.groupingBy(User::getId));
        // 创建题目用户id 与 创建题目用户的映射
        Map<Long, List<User>> createUserIdUserListMap = userFeignClient.listByIds(createUserIds).stream().collect(Collectors.groupingBy(User::getId));

        // 填充信息
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream().map(questionSubmit -> {
            // 如果不为管理员并且也不为本人
            QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
            if (!userFeignClient.isAdmin(currentUser) && !Objects.equals(currentUser.getId(), questionSubmit.getUserId())) {
                questionSubmitVO.setCode(null);
            }
            Long submitUserId = questionSubmitVO.getUserId();
            User submitUser = null;
            if (submitUserIdUserListMap.containsKey(submitUserId)) {
                submitUser = submitUserIdUserListMap.get(submitUserId).get(0);
            }
            Long questionId = questionSubmitVO.getQuestionId();
            Question question = null;
            if (userIdQuestionListMap.containsKey(questionId)) {
                question = userIdQuestionListMap.get(questionId).get(0);
            }
            // 存入题目对应创建用户
            Long createUserId = null;
            if (question != null) {
                createUserId = question.getUserId();
            }
            User createUser = null;
            if (createUserIdUserListMap.containsKey(createUserId)) {
                createUser = createUserIdUserListMap.get(createUserId).get(0);
            }
            // 封装
            QuestionVO questionVO = QuestionVO.objToVo(question);
            if (questionVO != null) {
                questionVO.setUserVO(UserVO.objToVo(createUser));
            }

            questionSubmitVO.setUserVO(UserVO.objToVo(submitUser));
            questionSubmitVO.setQuestionVO(questionVO);
            return questionSubmitVO;
        }).collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }


}




